package com.nf.dao;

import com.nf.entity.Student;
import com.nf.util.HisConnectionImpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements StudentDao {

    private Connection conn;

    public Student getStudentById(int i) {
        conn = new HisConnectionImpl().getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        Student student = null;
        try {
            pst = conn.prepareStatement("select * from student where id=?");
            pst.setInt(1,i);
            rs = pst.executeQuery();
            if (  rs.next() ){
                student = new Student();
                student.setId( rs.getInt("id")  );
                student.setUserName(  rs.getString("user_name") );
                student.setSex( rs.getString("sex"));
                System.out.println("查到学生：id"+i);

            }else {
                student = null;
                System.out.println("查不到学生：id"+i);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            rs.close();
            pst.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return student;
    }

    public List<Student> getAllStudent() {
        List<Student> studentList = new ArrayList<Student>();
        conn = new HisConnectionImpl().getConnection();
        PreparedStatement pst = null;
        ResultSet rs = null;
        Student student = null;
        try {
            pst = conn.prepareStatement("select * from student");
            rs = pst.executeQuery();
            while (  rs.next() ){
                student = new Student();
                student.setId( rs.getInt("id")  );
                student.setUserName(  rs.getString("user_name") );
                student.setSex( rs.getString("sex"));
                System.out.println("查到学生");
                studentList.add(student);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            rs.close();
            pst.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return studentList;
    }
}
